package net.modul.dict.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.common.dao.GeneralDaoImpl;
import net.modul.dict.dao.DictDao;
import net.modul.dict.vo.DictSortVo;
import net.modul.dict.vo.DictVo;

import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

/**
 * 数据字典数据访问接口实现类
 * 
 * @author Administrator
 * 
 */
public class DictDaoImpl extends GeneralDaoImpl implements DictDao {

	@Override
	public Integer insert(DictVo bean) throws Exception {
		return gqr
				.insertKey(

						"insert into t_dictionary (dict_sort_id,dict_name,dict_num,flag) values (?,?,?,?)",
						bean);
	}

	@Override
	public void update(DictVo bean) throws Exception {
		gqr.updateByBean("update t_dictionary set dict_name=? where dict_id=?",
				bean);
	}

	@Override
	public void updateFlag(DictVo bean) throws Exception {
		gqr.updateByBean("update t_dictionary set flag=? where dict_id=?", bean);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map<String, Map<String, DictVo>> searchGroup() throws Exception {
		ResultSetHandler rsh = new ResultSetHandler() {
			public Map<String, Map<String, DictVo>> handle(ResultSet rs)
					throws SQLException {
				Map<String, Map<String, DictVo>> map = new HashMap<String, Map<String, DictVo>>();
				if (!rs.next()) {
					return null;
				}
				try {
					do {
						DictVo vo = new DictVo();
						vo.setDict_id(rs.getInt("dict_id"));
						Integer sort_id = rs.getInt("dict_sort_id");
						vo.setDict_sort_id(sort_id);
						vo.setDict_name(rs.getString("dict_name"));
						String num = rs.getString("dict_num");
						vo.setDict_num(num);
						Map<String, DictVo> list = map.get(String
								.valueOf(sort_id));
						if (list == null) {
							list = new HashMap<String, DictVo>();
							map.put(String.valueOf(sort_id), list);
						}
						list.put(num, vo);
					} while (rs.next());
				} catch (Exception e) {
					e.printStackTrace();
				}

				return map;
			}
		};
		Map<String, Map<String, DictVo>> rs = gqr
				.queryByBean(
						"select dict_id,dict_sort_id,dict_name,dict_num from t_dictionary where flag=0",
						rsh);
		return rs;
	}

	@Override
	public List<DictSortVo> searchDictSort() throws Exception {
		ResultSetHandler<List<DictSortVo>> rsh = new BeanListHandler<DictSortVo>(
				DictSortVo.class);
		List<DictSortVo> list = gqr
				.query("select dict_sort_id,sort_name,sort_num,system,level from t_dict_type",
						rsh);
		return list;
	}
}
